import { Barrier } from "./Barrier";
import { _decorator, ICollisionEvent, instantiate, Node, Prefab, tween, v3, Vec3 } from 'cc';
import { Group } from "./GameConstant";
import { Label3D } from "../../1/Label3D";
import { GameManager } from "./GameManager";
import { PoolManager } from "../AshFramework/Managers/PoolManager";
import { AudioManager, Audios } from "../AshFramework/Managers/AudioManager";
const { ccclass, property } = _decorator;

@ccclass('Stone')
export class Stone extends Barrier {

    @property({ type: Boolean })
    IsLast: Boolean = false;

    @property
    BankNoteNumber: number = 1;

    @property
    Hp: number = 100;

    @property(Node)
    NormalNode: Node = null;

    @property(Node)
    DamagedNode: Node = null;

    @property(Label3D)
    Label3D: Label3D = null;

    @property(Prefab)
    BankNotePrefab: Prefab = null;

    BankNotePos: Vec3 = Vec3.ZERO;
    DamagedNumber: number = 3;//能承受几个子弹后损伤
    // IsRepulsed: boolean = false;//是否已经击退过

    protected onLoad(): void {
        super.onLoad();
        this.Collider.on("onCollisionStay", this.onCollisionStay, this);
        this.BankNotePos = this.node.getWorldPosition().clone().add3f(0, 0.021, 0);
    }

    protected start(): void {
        this.DamagedNumber = this.Hp / 2;
        this.updateHp();
        this.initBankNote();
    }

    initBankNote() {
        for (let i = 0; i < this.BankNoteNumber; i++) {
            const bankNote: Node = instantiate(this.BankNotePrefab)
            bankNote.parent = this.node.parent;
            const pos = this.BankNotePos.add3f(0, 0.003 * i, 0);
            bankNote.setWorldPosition(pos);
        }
    }

    updateHp(number: number = 0) {
        this.Hp += number;
        if (this.Hp <= 0) this.Hp = 0;
        this.Label3D.string = this.Hp.toString();
    }

    onCollisionStay(event: ICollisionEvent) {
        if (event.otherCollider.getGroup() == Group.Bullet) {
            PoolManager.PutNode(event.otherCollider.node);
            this.collisionByBullet();
        } else if (event.otherCollider.getGroup() == Group.Weapon) {
            // if (this.IsRepulsed) return;
            // this.IsRepulsed = true;
            if (this.IsLast) {
                //游戏结束
                GameManager.Instance.gameFail();
            } else {
                GameManager.Instance.repulsed();
            }
        }
    }

    //被子弹碰撞
    collisionByBullet() {
        tween(this.node)
            .to(0.1, { scale: v3(1.1, 1.1, 1.1) })
            .to(0.1, { scale: v3(1, 1, 1) })
            .start();
        this.updateHp(-GameManager.Instance.Harm);
        if (this.Hp <= this.DamagedNumber) {
            this.NormalNode.active = false;
            this.DamagedNode.active = true;
        }
        if (this.Hp <= 0) {
            AudioManager.PlaySound(Audios.StonBroken);
            this.scheduleOnce(() => { this.node.destroy(); });
        } else {
            AudioManager.PlaySound(Audios.HitSton);
        }
    }

}


